import { Form, InputNumber, Space } from "antd"
import lessModule from "./index.module.less"
import { useEffect, useState } from "react"
import { $eventBus, $EventBus_off, $EventBus_on, $WarningLevelColor } from "../../../../common/utils"

// 主页-预警阈值表单组件
interface homePageWarningThresholdFormComponentInterface {
    sourceData: object
    change_formData: Function
}
const HomePage_WarningThresholdFormComponent: React.FC<homePageWarningThresholdFormComponentInterface> = (props) => {
    const [form] = Form.useForm()
    const [sourceData, setSourceData] = useState<object>({})
    const formGroupList = props.sourceData["type"] === "主变" ? [
        {
            label: "中性点直流DC1 预警",
            key: "dcCur",
            unit: "A"
        },
        {
            label: "中性点交流AC 预警",
            key: "acCur",
            unit: "A"
        },
        {
            label: "变压器振动VA 预警",
            key: "transVibrate",
            unit: "mm/s"
        },
        {
            label: "变压器噪声NI 预警",
            key: "transNoise",
            unit: "dB"
        },
        {
            label: "地表电位EP1 预警",
            key: "surfacePotential",
            unit: "V"
        },
    ] : [
        {
            label: "金属护套电流 预警",
            key: "warningValue",
            unit: "A"
        },
        {
            label: "回流线电流 预警",
            key: "warningValue",
            unit: "A"
        },
        {
            label: "架空接地线电流 预警",
            key: "warningValue",
            unit: "A"
        },
    ]

    const formItemList = [
        {
            label: "一级",
            key: "one",
            ruleData: ({ getFieldValue }) => ({
                validator(data: object, value: string) {
                    const key = data["field"].split(".")[0]
                    sourceData[key] ??= {}
                    sourceData[key]["one"] = value
                    setSourceData({ ...sourceData })
                    if (value === undefined || getFieldValue(key)?.["two"] === undefined || value > getFieldValue(data["field"].split(".")[0])?.["two"]) {
                        return Promise.resolve();
                    }
                    return Promise.reject(new Error('必须高于二级预警值'));
                },
            })
        },

        {
            label: "二级",
            key: "two",
            ruleData: ({ getFieldValue }) => ({
                validator(data: object, value: string) {
                    const key = data["field"].split(".")[0]
                    sourceData[key] ??= {}
                    sourceData[key]["two"] = value
                    setSourceData({ ...sourceData })
                    if (value === undefined || getFieldValue(key)?.["one"] === undefined || value < getFieldValue(data["field"].split(".")[0])?.["one"]) {
                        return Promise.resolve();
                    }
                    return Promise.reject(new Error('必须小于一级预警值'));
                },
            })
        },
    ]


    // 广播函数数据
    const eventBusFuncData = {
        // 提交操作
        submitOperation: () => {
            form.validateFields().then((data) => {
                props.change_formData(data)
            })
        }
    }
    useEffect(() => {
        $EventBus_on(eventBusFuncData)
        return () => {
            $EventBus_off(eventBusFuncData)
        }
    }, [])

    return (
        <div className={lessModule["homePageWarningThresholdFormComponent"]}>
            <header className={lessModule["homePageWarningThresholdFormComponent-header"]}>监测数据预警阀值（一级预警值必须高于二级预警值）</header>
            <main className={lessModule["homePageWarningThresholdFormComponent-main"]}>
                <Form
                    className={lessModule["homePageWarningThresholdFormComponent-main__form"]}
                    form={form}
                    initialValues={props.sourceData}
                >

                    {
                        formGroupList.filter((item) => "dataType" in props.sourceData ? item["label"].includes(props.sourceData["dataType"] as string) : item).map((item, idx) => (
                            <div key={`formItem${idx}`} className={lessModule["main-form__group"]}>
                                <div>{item["label"]}</div>
                                {
                                    formItemList.map((formItem, formIdx,) => (
                                        <Form.Item key={`formItemItem${formIdx}`} className={lessModule["form-group__item"]} shouldUpdate>
                                            <Space size={18} align="start">
                                                <Space size={9} align="start">
                                                    <div className={lessModule["group-item__label"]} style={{ color: $WarningLevelColor(formItem["label"]) }}>{formItem["label"]}</div>
                                                    <div className={lessModule["group-item__row"]} >
                                                        <span className={lessModule["item-row__label"]}>值：{!idx && "±"}</span>
                                                        <Form.Item
                                                            className={lessModule["form-group__item"]}
                                                            name={[item["key"], formItem['key']]}
                                                            required={false}
                                                            rules={[formItem["ruleData"]]}>
                                                            <InputNumber style={{ width: idx ? 150 : 140.5 }} placeholder="请输入" min={0} precision={2} step="0.01" addonAfter={item["unit"]} autoComplete="off" />
                                                        </Form.Item>
                                                    </div>
                                                </Space>
                                                <div className={lessModule["group-item__row"]} >
                                                    <span className={lessModule["item-row__label"]}>信息：</span>
                                                    <div className={lessModule["item-row__info"]}>中性点直流超过{formItem["label"]}预警阈值【{sourceData[item["key"]]?.[formItem["key"]] || props.sourceData[item["key"]]?.[formItem["key"]]}】</div>
                                                </div>
                                            </Space>
                                        </Form.Item>
                                    ))
                                }
                            </div>
                        ))
                    }

                </Form>
            </main>
        </div>
    )
}
export default HomePage_WarningThresholdFormComponent